package cc.linker.steplink.crm.merchant.service.impl;

import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchant.dao.acs.RechargeDao;
import cc.linker.steplink.crm.merchant.service.acs.RechargeService;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@EnableAsync
@Service
public class RechargeServiceImpl implements RechargeService {

    @Autowired
    private RechargeDao rechargeDao;

    @Autowired
    private PurchaseProcessService purchaseProcessService;

    @Autowired
    private PurchaseProcessDao purchaseProcessDao;

    @Autowired
    private WcPayProperties wcPayProperties;

    @Autowired
    private HttpService httpService;

    @Override
    public void add(Map<String, Object> params) {
        rechargeDao.add(params);
    }

    @Override
    public void updateTradeSn(Map<String, Object> params) {
        rechargeDao.updateTradeSn(params);
    }

    @Override
    public void transferBatch(Long id, String orderSn, String clintType) {
        Map<String, Object> params = new HashMap<>();
        String transfeSn = TransactionOrderUtil.TYPE_RECHARGE + purchaseProcessService.getUniquePrimaryKey();
        params.put("transfeSn", transfeSn);
        params.put("id", id);
        rechargeDao.updateTransferSn(params);
        String str[] = orderSn.split(",");
        List<String> orderSnList = Arrays.asList(str);
        List<Map> transferList = new ArrayList<Map>();
        for (String orderSno : orderSnList) {
            //根据orderSn获取亏损金额以及销售商在通联的customerId(后期会有销售商)
            Map orderMap = rechargeDao.getLossInfo(orderSno);
            String belongId = "";
            if (!StringUtils.isEmpty(orderMap.get("belongId"))) {
                belongId = orderMap.get("belongId").toString();
            }
            String orgId = "";
            if (!StringUtils.isEmpty(orderMap.get("orgId"))) {
                orgId = orderMap.get("orgId").toString();
            }
            Long lossAmount = 0l;
            if (!StringUtils.isEmpty(orderMap.get("lossAmount"))) {
                lossAmount = Long.valueOf(orderMap.get("lossAmount").toString());
            }
            String customerId = "";
            if (StringUtils.isEmpty(belongId)) {
                customerId = purchaseProcessDao.getAccountUidByOrgId(orgId);
            } else {
                customerId = purchaseProcessDao.getAccountUidByCustomerId(belongId);
            }
            if (lossAmount > 0 && !StringUtils.isEmpty(customerId)) {
                Map<String, Object> transferMap = new HashMap<>();
                transferMap.put("amount", lossAmount);
                transferMap.put("customerId", "");
                transferList.add(transferMap);
            }

        }
        if (transferList.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("orderSn", transfeSn);
            map.put("clintType", clintType);
            map.put("transferList", transferList);
            this.transferBatchToTL(map);
        }
    }

    @Override
    public String transferBatchToTL(Map<String, Object> map) {
        String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_TRANSFER_BATCH;
        try {
            Map<String, Object> resultMap = new HashMap<>();
            LOGGER.info("通联支付请求参数==={}", JSON.toJSONString(map));
            String result = httpService.doPost(url, JSON.toJSONString(map), WcPayConstant.JSON);
            resultMap = this.callResultProcess(result);
            return JSON.toJSONString(resultMap);
        } catch (Exception e) {
            LOGGER.error("支付网关调用异常", e);
            throw GlobalException.build("支付网关调用异常");
        }
    }


    /**
     * 调用结果处理(中金)
     */
    @Override
    public Map callResultProcess(String result) throws GlobalException {
        if (StringUtils.isEmpty(result)) {
            throw GlobalException.build("网关调用失败");
        }
        LOGGER.info(result);
        Map resMap = (Map) JSON.parse(result);
        if (!resMap.containsKey("code")) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        if (!"200".equals(resMap.get("code"))) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        if (!resMap.containsKey("data")) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        Map data = (Map) resMap.get("data");
        if (!data.containsKey("authCode")) {
            throw GlobalException.build("网关调用失败:" + resMap.get("msg"));
        }
        return data;
    }

    @Override
    public void updateStatus(Map<String, Object> params) {
        rechargeDao.updateStatus(params);
    }

    //修改亏损
    @Async
    @Override
    public void isLoss(String orderSn) {
        Integer isLoss = 0;
        Integer lossAmount = rechargeDao.isLoss(orderSn);
        if (lossAmount <= 0) {
            rechargeDao.updateIsLoss(orderSn, isLoss);
            rechargeDao.updateProtectIsLoss(orderSn, isLoss);
        }
    }
}
